Vue.component('user-select', {
  template: `
      <el-select
        v-bind="$attrs"
        v-on="$listeners"
        ref="select"
        :multiple="multiple"
        :value="selectData.label"
        :popper-append-to-body="true"
        :collapse-tags="collapseTags"
        :filter-method="filterMethod"
        :disabled="disabled"
        filterable
        clearable
        @visible-change="visibleChange"
        @remove-tag="removeTag"
        @clear="clear"
        :placeholder="translate('选择用户')"
      >
        <el-tree
          class="userTree"
          slot="empty"
          ref="tree"
          :indent="10"
          :data="treeData"
          node-key="id"
          default-expand-all
          :props="defaultProps"
          :show-checkbox="multiple"
          @node-click="handleNodeClick"
          :filter-node-method="filterNodeMethod"
          @check="checkBox"
        >
          <span slot-scope="{ node, data }" class="custom-tree-node">
            <span v-if="data.deptOrUser === 'dept'">
              <i class="dept-icon"></i>
              <p>{{ node.label }}</p>
            </span>
            <span v-if="data.deptOrUser === 'user'" :class="{disableChoose: disableChoose(data)}">
              <i class="user-icon"></i>
              <p>{{ node.label }}</p>
            </span>
          </span>
        </el-tree>
    </el-select>
  `,
  props: {
    treeData: {
      type: Array,
      default: () => []
    },
    value: {
      type: [String, Array],
      default: () => ''
    },
    defaultUser: {
      type: Boolean,
      default: false
    },
    // 人员过多用 +N  展示
    collapseTags: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data: function() {
    return {
      selectData: {},
      popoverVisible: false,
      multiple: false,
      defaultProps: {
        children: 'children',
        label: 'label',
        disabled: 'disabled'
      },
      storageLanguageJson: {}
    }
  },
  watch: {
    selectData(data) {
      this.emit(data.value)
    },
    value(value) {
      if (value && value.indexOf('[') > -1) {
        let json = value.replace(', ', '\", \"')
        json = json.replace('[', '[\"')
        json = json.replace(']', '\"]')
        json = JSON.parse(json)
        this.checkValue(json)
      } else {
        this.checkValue(value)
      }
    }
  },
  computed: {
    allList() {
      return this.treeToArray(this.treeData)
    }
  },
  created: function(){
    if (window.localStorage['language']) {
      var localStorage = window.localStorage['language']
      this.storageLanguageJson = JSON.parse(window.localStorage['language_' + localStorage])
    }
  },
  mounted() {
    if(this.$attrs.multiple !== undefined) {
      this.multiple = true
      this.selectData = {
        value: [],
        label: []
      }
    } else {
      this.multiple = false
      this.selectData = {
        value: '',
        label: ''
      }
    }
    if (this.getParameter('formId') && this.defaultUser) {
      this.$nextTick(() => {
        this.checkValue(window.parent.currentLoginUserId)
      })
    }
  },
  methods: {
    translate(key) {
      if (window.localStorage['language'] && window.localStorage['language'] !== 'zh_cn') {
        setTimeout(() => {
          for (var i in this.storageLanguageJson) {
            if (i === key) {
              // console.log(this.storageLanguageJson[i])
              return this.storageLanguageJson[i]
            } else {
              return key
            }
          }
        }, 1000);
      } else {
        return key
      }
    },
    getParameter: function (name) {
      var query = window.location.search.substring(1);
      if(query!==''){
        var vars = query.split("&");
        for (var i=0;i<vars.length;i++) {
          var pair = vars[i].split("=");
          if(pair.length === 2){
            if(pair[0] === name){return pair[1];}
          }
        }
      }
      return null;
    },
    treeToArray(array, children = 'children') {
      let result = []
      const data = this.deepClone(array)
      data.forEach(item => {
        if (!item[children]) {
          result.push(item)
        } else {
          const child = item[children]
          delete item[children]
          result.push(item)
          result = result.concat([], this.treeToArray(child))
        }
      })
      return result
    },
    deepClone(source) {
      if (!source && typeof source !== 'object') {
        throw new Error('error arguments', 'deepClone')
      }
      const targetObj = source.constructor === Array ? [] : {}
      Object.keys(source).forEach(keys => {
        if (source[keys] && typeof source[keys] === 'object') {
          targetObj[keys] = this.deepClone(source[keys])
        } else {
          targetObj[keys] = source[keys]
        }
      })
      return targetObj
    },
    visibleChange(visible) {
      this.popoverVisible = visible
      if (visible) {
        this.$refs.tree.filter('')
      }
    },
    disableChoose(data) {
      return !data.choose && !data.children?.length
    },
    filterMethod(value) {
      this.$refs.tree.filter(value)
    },
    removeTag(value) {
      const index = this.selectData.label?.findIndex(item => item === value)
      this.selectData.label.splice(index, 1)
      this.selectData.value?.splice(index, 1)
      this.$nextTick(()=> {
        this.$refs.tree.setCheckedKeys(this.selectData.value)
      })
    },
    filterNodeMethod(value, data) {
      if (!value) return true
      return data.label?.indexOf(value) !== -1
    },
    checkValue(value) {
      if (!value) {
        return
      }
      if (this.multiple) {
        this.$refs.tree.setCheckedKeys(value)
        const data = this.$refs.tree.getCheckedNodes(true)
        if(data && data.length > 0){
          this.selectData = {
            label: data.map(item => item.label),
            value: value
          }
        }
      } else {
        const item = this.allList.find(item => item.id === value) || {}
        this.selectData = {
          value: item.id,
          label: item.label
        }
      }
    },
    handleNodeClick(data) {
      if (!this.multiple && data.choose) {
        this.selectData = {
          value: data.id,
          label: data.label || ''
        }
        this.$refs.select.blur()
        this.popoverVisible = false
      }
    },
    checkBox() {
      this.handleCheckChange()
    },
    handleCheckChange() {
      const data = this.$refs.tree.getCheckedNodes(true)
      this.selectData = {
        label: data.reduce((results, item) => {
          if (item.label) {
            return [...results, item.label]
          }
          return results
        }, []),
        value: data.map(item => item.id)
      }
    },
    clear() {
      if(this.multiple) {
        this.selectData = {
          value: [],
          label: []
        }
      } else {
        this.selectData = {
          value: '',
          label: ''
        }
      }
    },
    emit(value) {
      this.$emit('change', value)
      this.$emit('input', value)
    }
  }
})
